
const executeModel = async (strcomms) => {
  if (
    strcomms.some(
      (a) => a.comm.componentKey === "modal" || a.comm.componentKey === "table"
    )
  ) {
    let str = `const Open_Modal = (index) => {
  currentIndex.value = index;
  modalRef.value?.showModal();
};

const Close_Modal = () => {
  modalRef.value?.resetFields();
  modalRef.value?.close();
};
const Confirm_Modal = async (val) => {
  const type = modal.apiType;
  const vals = Object.assign({}, val, modal.value.row);
  fetchTableApi(type, vals, modal.value.index);
};`;
    return str;
  } else {
    return "";
  }
};

// 递归处理函数
const dep = async (comm, fun) => {
  if (!Array.isArray(comm) || comm.length === 0) return;

  const promises = comm.map(async (a) => {
    try {
      await fun(a);
      if (a.children && Array.isArray(a.children) && a.children.length > 0) {
        await dep(a.children, fun);
      }
    } catch (error) {
      console.error(`处理项目 ${JSON.stringify(a)} 时出错:`, error);
      throw error; // 根据需求决定是否重新抛出错误
    }
  });

  return await Promise.all(promises);
};

// url转驼峰
const toHump = (str) => {
  return str
    .replace(/(?:^\w|[A-Z]|\b\w)/g, (letter, index) =>
      index === 0 ? letter.toLowerCase() : letter.toUpperCase()
    )
    .replace(/\s+/g, "")
    .replace(/\//g, "");
};

const executeEventsEmits = async (strcomm) => {
  if (Array.isArray(strcomm) && strcomm.length > 0) {
    const fraw = {
      form: (as, nm) => {
        let index = -1;
        if (as.assign) {
          index = strcomm.findIndex((a) => a.comm.index === as.assign);
          if (index < 0) return "";
          let asr = {
            Form__Search: `
          const Pcf = Object.values(pageConfig.value).flat();
          let Ci = -1;
          if (comm.assign) {
            Ci = Pcf.findIndex((a) => a.index === comm.assign);
          }
          if (Ci > -1) {
            compId.value[Ci]?.fetchData();
          }`,
          };

          return {
            asr: asr[nm] || "",
            fns: "",
          };
        } else {
          const fn = toHump(as.apiUrl);
          let asr = {
            Form__Search: fn ? `fetch${fn}(val.formData)` : "",
          };
          return {
            asr: asr[nm] || "",
            fns: "",
          };
        }
      },
      table: (as, nm, comm) => {
        const index = strcomm.findIndex((a) => a.componentKey === "table");
        if (index < 0) return "";
        let asr = {
          Table_Modal__Open: `
          modal.apiType = btnInfo.key;
          Open_Modal(comm.index);`,
          Table_Modal__Close: `
          Close_Modal(comm.index);
          `,
          Table_Operate__Change: `
          modal.apiType = btnInfo.key;
          if (btnInfo.key === "delete") {
            confirmDelete(comm, btnInfo, row);
          } else {
            Open_Modal(comm.index);
            const val = getTableRowValue(comm, btnInfo, row);
            nextTick(() => {
              modalRef.value?.setForm(val);
            });
          }`,
        };
        let fns = ``;
        return {
          asr: asr[nm] || "",
          fns: fns,
        };
      },
      list: (as, nm, comm, args) => {
        let asr = {
          List_Onload: `if (item2.index === comm.index) {
    fetch${toHump(as.apiUrl)}(${args});
  }`,
        };
        return {
          asr: asr[nm] || "",
          fns: "",
        };
      },
    };
    let cn = [];
    let fn = [];
    strcomm.map((a) => {
      const reg = new RegExp(
        /emit\(["']([a-zA-Z0-9_-]+)["'](\,\s?([a-zA-Z0-9_-\s,]+))?\)/g
      );
      a.commstr.replace(reg, (str, $1, $2, $3) => {
        console.log(a.componentKey, ".componentKey");
        let ex = "";
        if (fraw[a.componentKey]) {
          let args = $3 ? `${$3}` : "";
          let s3 = $3 ? `${$3}` : "";
          const bn = fraw[a.componentKey](a.comm, $1, a.comm, s3);
          if (bn && bn.asr) {
            ex = bn.asr;
            // let ae = bn.match(/\([a-zA-Z0-9_-]+\)/g);

            let an = `@${$1}="(${s3}) => { ${$1}(item2, ${args}) }"`;
            if (bn.fns && !fn.includes(bn.fns)) {
              fn.push(bn.fns);
            }
            if (!cn.includes(an)) {
              cn.push(an);
              fn.push(`const ${$1} = (item2, ${args}) => { ${ex} }`);
            } else {
              const idx = fn.findIndex(
                (a) => a.indexOf(`const ${$1} = (item2, ${args})`) > -1
              );
              if (idx > -1) {
                fn[idx] = fn[idx].replace(/{(\s?\n?(.*?)\s?\n?)}/g, `$1${ex}`);
              }
            }
          }
        }
      });
    });
    return {
      cn,
      fn,
    };
  } else {
    return [];
  }
};

const executeApi = async (strcomms, _modals) => {
  const apiUrls = new Set();
  const methods = new Set();
  const executes = new Set();
  const emits = await executeEventsEmits(strcomms);
  console.log(emits, "emits");
  const excuteCommApi = {};
  let comms = [];
  let allComms = [];
  const promises = strcomms.map(async (strcomm) => {
    try {
      let a = { ...strcomm.comm, ...strcomm.comm.attrs };

      if (a.options && a.options.indexOf("Filters") === -1) {
        a.apiUrl = a.options;
      }

      console.log(a, "++++++aaa++++++");
      if (!a.apiUrl) {
        if (a.index && a.index.split("-").length < 3) {
          comms.push(a);
        }
        return;
      }



      const apis = a.apiUrl.split("|");
      let i = 0;
     
      await dep(apis, async (apiUrl) => {
        apiUrl = apiUrl.split(":");
        apiUrl = apiUrl[0];
        const fn = toHump(apiUrl);

        const importStatement = `import { ${fn} } from "@/apis${apiUrl}";`;
        if (
          a.componentKey === "list" ||
          a.componentKey === "banner" ||
          a.componentKey === "form"
        ) {
          const args = {
            list: "comm, page",
            form: "val",
          };
          const vars = a.pageSize
            ? `list.value["${a.index}"].concat(data.list || data || [])`
            : `data.list || data || []`;
          const estr = {
            list: `if (!list.value["${a.index}"]) list.value["${a.index}"] = [];
                  list.value["${a.index}"] = ${vars};`,
            banner: `if (!list.value["${a.index}"]) list.value["${a.index}"] = [];
                  list.value["${a.index}"] = ${vars};`,
            form: `message.success("操作成功！")`,
          };
          const ers = args[a.componentKey]
            ? typeof args[a.componentKey] === "object"
              ? `{...${args[a.componentKey]}}`
              : `${args[a.componentKey]}`
            : "";
          const params = a.pageSize
            ? `{ page: page || 1, limit: ${a.pageSize || 10}}`
            : `${ers}`;
          const fetchFunction = `
          const fetch${fn} = async (${args[a.componentKey] || ""}) => {
            try {
              const { code, data } = await ${fn}(${params});
              if (code === rescf.codeVal) {
                ${estr[a.componentKey] || ""}
              }
            } catch (error) {
              console.error('Error fetching data:', error);
            }
          };
        `;

          const executeCall = `fetch${fn}();`;

          apiUrls.add(importStatement);
          methods.add(fetchFunction);
          if (a.componentKey !== "form") {
            executes.add(executeCall);
          }
        } else if (a.componentKey === "table") {
          if (!excuteCommApi[a.index]) excuteCommApi[a.index] = {};
          const gs = {
            0: "apiGet",
            1: "apiPost",
            2: "apiPut",
            3: "apiDelete",
          };
          excuteCommApi[a.index][toHump(`${gs[i]}/` + fn)] = fn;
          const modal = _modals.find((m) => m.index === a.index);
          const confirmDelete = a.btns.includes("delete")
            ? `const confirmDelete = (comm, btnInfo, row) => {
            const val = getTableRowValue(comm, btnInfo, row);
            Modal.confirm({
                title: "提示",
                content: "确定删除吗？",
                onOk() {
                  fetchTableApi("delete", val, comm.index);
                },
                onCancel() {},
              });
          };`
            : "";
          const mf = a.btns.every((value) =>
            ["add", "edit", "delete", "view"].includes(value)
          )
            ? `const getTableRowValue = (comm, btnInfo, row) => {
                if (btnInfo.key === "add") return {};
                const val = { ...row };
                const modal = modals.value.find((a) => a.index === comm.index);
                Object.keys(val).forEach((key) => {
                  const attr = modal.attrs.find((a) => a.field === key);
                  if (attr && attr.arr2str && val[key]) {
                    val[key] = val[key].split(",");
                  }
                });
                modal.row = val;
                return val;
              };`
            : "";
          const fetchFunction = `${confirmDelete}${mf}const getTableApis = (comm, gs) => {
            const type = gs.substr(0, 1).toUpperCase() + gs.substr(1);
            const fn = Object.keys(comm).find((a) => a.indexOf(type) > -1);
            return comm[fn];
          };
          const fetchTableApi = async (gs, val, index) => {
            const Pcf = Object.values(pageConfig.value).flat(); 
            const Cp = Pcf.find((a) => a.index === index);
            const Api = getTableApis(Cp, gs);
            const { code, msg } = await Api(val);
            if (code === rescf.codeVal) {
              commId.value?.[Ci].fetchData();
              Close_Modal();
            } else {
              message.error(msg);
            }
          };
          `;
          a = Object.assign({}, a, excuteCommApi[a.index], {
            modalTitle: modal.title || "",
          });
          methods.add(fetchFunction);
          apiUrls.add(importStatement);
        } else {
          if (!excuteCommApi[a.index]) excuteCommApi[a.index] = {};
          excuteCommApi[a.index][toHump(fn)] = fn;
          a = Object.assign({}, a, excuteCommApi[a.index]);
          apiUrls.add(importStatement);
        }
        i++;

        if (a.index && a.index.split("-").length < 3) {
          const ci = comms.findIndex((b) => b.index === a.index);
          if (ci > -1) {
            comms[ci] = a;
            allComms[ci] = a;
          } else {
            comms.push(a);
            allComms.push(a);
          }
        } else {
          const ci = comms.findIndex((b) => b.index === a.index);
          if (ci > -1) {
            allComms[ci] = a;
          } else {
            allComms.push(a);
          }
        }
        return a;
      });
    } catch (error) {
      console.error("Error processing component:", error);
    }
  });

  const p = await Promise.all(promises);
  const modals = await executeModel(strcomms);
  return {
    comms,
    allComms,
    excuteCommApi: excuteCommApi,
    apiUrls: Array.from(apiUrls),
    methods: Array.from(methods),
    executes: Array.from(executes),
    modals,
    emits: emits,
  };
};

module.exports = executeApi;